<?php

if_get('/engine_rules', function ()
{/*{{{*/
    list(
        $inputs['rule'], $inputs['event_id']
    ) = input_list(
        'rule', 'event_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $engine_rules = dao('engine_rule')->find_all_by_column($inputs);

    return [
        'count' => count($engine_rules),
        'engine_rules' => array_build($engine_rules, function ($id, $engine_rule) {
            return [
                null,
                [
                    'id' => $engine_rule->id,
                    'rule' => $engine_rule->rule,
                    'event_display' => $engine_rule->event->display_for_engine_rules_event(),
                    'create_time' => $engine_rule->create_time,
                    'update_time' => $engine_rule->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/engine_rules/add', function ()
{/*{{{*/
    $rule = input('rule');
    otherwise_error_code('ENGINE_RULE_REQUIRE_RULE', $rule);

    $engine_rule = engine_rule::create(
        $rule
    );

    $engine_rule->event = dao('event')->find(input('event_id'));

    return [
        'id' => $engine_rule->id,
    ];
});/*}}}*/

//todo::detail

if_post('/engine_rules/update/*', function ($engine_rule_id)
{/*{{{*/
    $rule = input('rule');

    $engine_rule = dao('engine_rule')->find($engine_rule_id);
    otherwise_error_code('ENGINE_RULE_NOT_FOUND', $engine_rule->is_not_null());

    $engine_rule->event = dao('event')->find(input('event_id'));
    $engine_rule->rule = $rule;

    return true;
});/*}}}*/

if_post('/engine_rules/delete/*', function ($engine_rule_id)
{/*{{{*/
    $engine_rule = dao('engine_rule')->find($engine_rule_id);
    otherwise_error_code('ENGINE_RULE_NOT_FOUND', $engine_rule->is_not_null());

    $engine_rule->delete();

    return true;
});/*}}}*/
